/**
 *
 */
package com.storm.lib.util;

import java.util.List;
import java.util.Random;

/**
 * 类功能: 随机工具类
 * @author johnny
 * @version 2010-12-21
 */
public class RandomUtil {

	/**
	 * 方法功能:根据概率随机
	 * 更新时间:2010-12-21, 作者:johnny
	 * @param i
	 * @return
	 */
	public static boolean random(int percentage) {
		Random random = new Random();
		//1~100
		int result = random.nextInt(100)+1;
		if(result<=percentage){
			return true;
		}
		return false;
	}

	/**
	 * 方法功能:根据概率组返回对象
	 * 更新时间:2010-12-21, 作者:johnny
	 * @param objs
	 * @param percentages
	 * @return
	 */
	public static Object randomObjectByPecentage(List<Object> objs, Integer[] percentages) {
		if(percentages.length!=objs.size()){
			ExceptionUtil.throwInvalidParamException();
		}
		int totalPercentage = IntUtil.getSum(percentages);
		if(totalPercentage<percentages.length){
			ExceptionUtil.throwInvalidParamException();
		}
		//TODO 复查-检查概率
		int randomNum = IntUtil.getRandomInt(0, totalPercentage);
		int currentValue = 0;
		for (int i = 0; i < percentages.length; i++) {
			currentValue+=percentages[i];
			if(randomNum<=currentValue){
				return objs.get(i);
			}
		}
		ExceptionUtil.throwInvalidParamException();
		return null;
	}

	/**
	 *
	 * 更新时间:2011-2-12, 作者:johnny
	 * 方法功能:根据概率随机出一个数
	 * @param weight
	 * @param vals
	 * @return
	 */
	public static Object randomObjectByPecentage(List<Object> vals, List<Integer> weight) {
		Integer[] values = weight.toArray(new Integer[weight.size()]);
		return randomObjectByPecentage(vals,values);
	}
	/**
	 * 方法功能:随机一个指定位小数的double值
	 * @author future 2011-10-13
	 * @param length
	 * @return
	 */
	public static double randomDouble(int length){
		Random random = new Random();
		double d1 = random.nextDouble();
		double d2 = DoubleUtil.doubleFormat(d1, length);
		return d2;
	}
}
